<!DOCTYPE HTML>
<!--suppress ALL-->
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>用户管理</title>
    <link rel="icon" href="#">
    <script id="header" type="text/javascript" src="../js/header.js?head=../"></script>
    <script id="layui" type="text/javascript" src="../js/lib/layui/layui.js"></script>
    <link rel="stylesheet" href="../js/lib/layui/css/layui.css" />
    <style type="text/css">
        .hint-text{
            font: 14px/150% "";
            color: red;
        }
    </style>
</head>
<body>
<nav class="breadcrumb">
    <i class="Hui-iconfont">&#xe67f;</i> 首页 <span class="c-gray en">&gt;</span>
    修改标题 <a class="btn btn-success radius r mr-20"
            style="line-height: 1.6em; margin-top: 3px"
            href="javascript:location.replace(location.href);" title="刷新"><i
                class="Hui-iconfont">&#xe68f;</i></a>
</nav>
<!--
<iframe scrolling="yes" frameborder="0" src="templates/plugins/regionSelector.ftl"></iframe>
-->
<div class="pd-20">
    <div class="text-l">
            搜索条件：
            <input type="text"  class="input-text" id="search" name="search" placeholder="请输入" style="width:120px;">
            账号状态：
            <select class="select"  name="userStatus" id="userStatus" size="1" style="width:120px;">
                <option value="-1" selected>不限</option>
                <option value="00">正常</option>
                <option value="01">停用</option>
            </select>
            <input type="button" class="btn btn-secondary radius" value="搜索" onclick="searchData()">
        </div>

    <div class="cl pd-5 bg-1 bk-gray mt-20">
			<span class="l">
                <a href="javascript:;" onclick="javascript:add();" id="saveData" class="btn btn-primary radius">
                    <i class="Hui-iconfont">&#xe600;</i>新增
                </a>
                <a href="javascript:;" onclick="bathDelete();" id="deleteData" class="btn btn-danger radius">
                    <i class="Hui-iconfont">&#xe6e2;</i> 批量删除
                </a>
			</span>
    </div>
    <div class="mt-20">
        <table class="table table-border table-bordered table-hover table-bg table-sort" id="main">
            <thead>
                <tr class="text-c">
                    <th width="25"><input type="checkbox" name="" value=""></th>
                    <th width="50">ID</th>
                    <th width="100">登录名</th>
                    <th width="100">用户名</th>
                    <th width="100">用户类型</th>
                    <th width="100">帐号状态</th>
                    <th width="100">创建时间</th>
                    <th width="100">上次登录时间</th>
                    <th width="100">创建者</th>
                    <th width="140">操作</th>
                </tr>
            </thead>
        </table>
    </div>
</div>

<div id="formShow" class="pd-20" style="display: none;">
    <form action="" method="post" class="form form-horizontal" id="submitForm">
        <!-- 账号、密码 -->
        <div class="row cl">
            <input id="id" name="id" style="display: none;" />
            <input id="dataType" name="dataType" style="display: none;" />
            <label class="form-label col-xs-2 col-sm-2" for="loginName">
                <span class="c-red">*</span>账&#12288;&#12288;号：
            </label>
            <div class="formControls col-xs-4 col-sm-4">
                <input type="text" class="input-text" value="" placeholder="" id="loginName" name="loginName">
                <span class="hint-text"></span>
            </div>
            <label class="form-label col-xs-2 col-sm-2" for="password">
                <span class="c-red">*</span>密&#12288;&#12288;码：
            </label>
            <div class="formControls col-xs-4 col-sm-4">
                <input type="password" class="input-text" value="" placeholder="" id="password" name="password" >
                <span class="hint-text"></span>
            </div>
        </div>

        <!-- 昵称、性别 -->
        <div class="row cl">
            <label class="form-label col-xs-2 col-sm-2">
                <span class="c-red">*</span>昵&#12288;&#12288;称：
            </label>
            <div class="formControls col-xs-4 col-sm-4">
                <input type="text" class="input-text" value="" placeholder="" id="userName" name="userName">
                <span class="hint-text"></span>
            </div>
            <label class="form-label col-xs-2 col-sm-2">
                <span class="c-red">*</span>性&#12288;&#12288;别：
            </label>
            <div class="formControls col-xs-4 col-sm-4">
                <span class="select-box">
                    <select class="select valid" size="1" name="sex" id="sex">
                        <option value="0">男</option>
                        <option value="1">女</option>
                        <option value="2" selected>保密</option>
                    </select>
                </span>
                <span class="hint-text"></span>
            </div>
        </div>

        <!-- 账户类型, 账号状态 -->
        <div class="row cl">
            <label class="form-label col-xs-2 col-sm-2">
                <span class="c-red">*</span>账户类型：
            </label>
            <div class="formControls col-xs-4 col-sm-4">
                <span class="select-box">
                    <select class="select valid" size="1" name="userType" id="userType">
                        <option value="00">系统用户</option>
                        <option value="01">普通用户</option>
                    </select>
                </span>
                <span class="hint-text"></span>
            </div>
            <label class="form-label col-xs-2 col-sm-2">
                <span class="c-red">*</span>账户状态：
            </label>
            <div class="formControls col-xs-4 col-sm-4">
                <span class="select-box">
                    <select class="select valid" size="1" name="status" id="status">
                        <option value="0">启用</option>
                        <option value="1">停用</option>
                    </select>
                </span>
                <span class="hint-text"></span>
            </div>
        </div>

        <!-- 电话、邮箱 -->
        <div class="row cl">
            <label class="form-label col-xs-2 col-sm-2" for="phonenumber">
                <span class="c-red">*</span>电&#12288;&#12288;话：
            </label>
            <div class="formControls col-xs-4 col-sm-4">
                <input type="text" class="input-text" id="phonenumber" name="phonenumber">
                <span class="hint-text"></span>
            </div>
            <label class="form-label col-xs-2 col-sm-2" for="email">
                <span class="c-red">*</span>邮&#12288;&#12288;箱：
            </label>
            <div class="formControls col-xs-4 col-sm-4">
                <input type="text" class="input-text" value="" placeholder="" id="email" name="email">
                <span class="hint-text"></span>
            </div>
        </div>

        <!-- 角色 -->
        <div class="row cl">
            <label class="form-label col-xs-2 col-sm-2" for="phonenumber">
                <span class="c-red">*</span>角&#12288;&#12288;色：
            </label>
            <div class="formControls col-xs-4 col-sm-4" id="role">
                <p></p>
                <span class="hint-text"></span>
            </div>
        </div>

        <!-- 备注 -->
        <div class="row cl">
            <label class="form-label col-xs-2 col-sm-2" for="remark">
                <span class="c-red">*</span>备&#12288;&#12288;注：
            </label>
            <div class="formControls col-xs-6 col-sm-10">
                <textarea name="remark" id="remark" style="width: 100%; height: 100px; resize:none;"></textarea>
                <span class="hint-text"></span>
            </div>
        </div>

        <div class="row cl">
            <div class="col-9 col-offset-3">
                <input class="btn btn-primary radius" id="submit" type="submit" value="提交">
            </div>
        </div>
    </form>
</div>
<script type="text/javascript">
    let base = "../sysUser/";
    let findPage = "findSysUserPage";
    let findOne = "findSysUserOne";
    let updateData = "updateSysUser";
    let saveData = "saveSysUser";
    let deleteData = "deleteSysUser";
    let getRole = "getRoleById";
    let getUserRole = "getUserRole";
    let pageUrl = base + findPage;
    let editUrl = base + findOne;
    let updateUrl = base + updateData;
    let addUrl = base + saveData;
    let deleteUrl = base + deleteData;
    let getRoleUrl = base + getRole;
    let getUserRoleUrl = base + getUserRole;
    let pageSize = 7;
    let dataTable;
    let globalPassword = [];
    let loginUser = {"id": 1,"name": "Marisa"}; // 暂定为用户对象，保存当前登录对象的基本信息，用户退出登录或下线后自动清除
    $(function() {
        // 数据表格渲染
        dataTable = MyDataTable({
            id : "main",
            pageUrl : pageUrl,
            param : function() {
                let o = {"keywords": $("#search").val(), "status": $("#userStatus").val()};
                o = JSON.stringify(o);
                console.log(o);
                return {"str": o};
            },
            "columns" : [
                {
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        return '<td><input name="" type="checkbox" value="'+full.id+'"></td>';
                    }
                },
                {   // ID
                    "data" : "id",
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        if (data) {
                            return data;
                        }
                        return "";
                    }
                },
                {   // 登录名
                    "data" : "loginName",
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        if (data) {
                            return data;
                        }
                        return "";
                    }
                },
                {   // 用户名
                    "data" : "userName",
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        if (data) {
                            return data;
                        }
                        return "";
                    }
                },
                {   // 用户类型
                    "data" : "userType",
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        if(data != null){
                            return data == "00" ? "系统用户": "普通用户"
                        }
                        return "";
                    }
                },
                {   // 帐号状态
                    "data" : "status",
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        if (data) {
                            return data == "0" ? "正常" : "停用";
                        }
                        return "";
                    }
                },
                {   // 创建时间
                    "data" : "createTime",
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        if (data) {
                            return data;
                        }
                        return "";
                    }
                },
                {   // 上次登录时间
                    "data" : "loginDate",
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        if (data) {
                            return data;
                        }
                        return "";
                    }
                },
                {   // 创建者
                    "data" : "createBy",
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        if (data) {
                            return data;
                        }
                        return "";
                    }
                },
                {
                    "orderable" : false,
                    "className" : 'text-c',
                    "render" : function(data, type, full) {
                        return "<a class="
                                + updateData
                                + "  title = '修改' onclick='edit(\""
                                + full.id
                                + "\");'><i class='Hui-iconfont'>&#xe6df;</i></a>"
                                + "&#12288;"
                                + "<a  class="
                                + deleteData
                                + "  title = '删除' onclick='deletePlat(\""
                                + full.id
                                + "\");'><i class='Hui-iconfont'>&#xe6e2;</i></a>";
                    }
                }]
        })

        // 自定义规则：登录名
        $.validator.addMethod("verifyLoginName", function(value, element) {
            let tel = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/;
            return this.optional(element) || (tel.test(value));
        }, "Error. custom rules: verifyLoginName");

        // 自定义规则：用户名
        $.validator.addMethod("verifyUserName", function(value, element) {
            let tel = /^([a-zA-Z0-9_-]|[\u4E00-\u9FA5]){4,20}$/;
            return this.optional(element) || (tel.test(value));
        }, "Error. custom rules: verifyUserName");

        // 自定义规则：密码
        $.validator.addMethod("verifyPassword", function(value, element) {
            let regExp = /^(?=.*\d)(?=.*[a-zA-Z])[\da-zA-Z~!@#$%^&*.]{6,18}$/;
            return this.optional(element) || (regExp.test(value));
        }, "Error. custom rules: verifyPassword");

        // 自定义规则：电话号码
        $.validator.addMethod("verifyPhoneNumber", function(value, element) {
            let tel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
            return this.optional(element) || (tel.test(value));
        }, "Error. custom rules: verifyPhoneNumber");

        // 自定义规则：邮箱验证
        $.validator.addMethod("verifyEmail", function(value, element) {
            let tel = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
            return this.optional(element) || (tel.test(value));
        }, "Error. custom rules: verifyEmail");

        // 自定义规则：备注验证
        $.validator.addMethod("verifyRemark", function(value, element) {
            let tel = /^.{0,64}$/;
            return this.optional(element) || (tel.test(value));
        }, "Error. custom rules: verifyRemark");

        $("#submitForm").validate({
            rules: {
                loginName:{
                    required : true,
                    verifyLoginName: true
                },
                userName: {
                    required : true,
                    verifyUserName: true
                },
                password: {
                    required: ()=>{
                        let pwd = document.querySelector("#password");
                        let tag = pwd.dataset.tag;
                        let str = pwd.value;
                        let b = tag !== "0" && str.length < 1;
                        // console.log("required>>: ", pwd.value, pwd.value.length, tag),b;
                        return b;
                    },
                    verifyPassword: () => {
                        let pwd = document.querySelector("#password");
                        let tag = pwd.dataset.tag;
                        let str = pwd.value;
                        let b = tag !== "0" && str.length < 1;
                        // console.log("password>>: ", pwd.value, pwd.value.length, tag);
                        return b;
                    }
                },
                phonenumber: {
                    required: true,
                    verifyPhoneNumber: true,
                    digits: true
                },
                email: {
                    required: true,
                    verifyEmail: true
                },
                remark: {
                    required: true,
                    verifyRemark: true
                },
            },
            messages: {
                loginName: "请输入包含数字字母下划线的账号，长度为4-16位",
                userName: "请输入包含汉字、数字、大小写字母、下划线的用户名，长度为4-20位",
                password: "请输入6-18位包含大小写字母、数字、特殊符号的密码",
                phonenumber: "请输入正确的手机号",
                email: "请输入正确的邮箱",
                remark: "备注请控制在64字符以内",
            },
            submitHandler: function (form) {
                submitFrom();
                return false; // 阻止表单自动提交事件
            }
        });
    });

    /**
     * 删除方法
     * */
    function bathDelete() {
        let ids = [];
        $("#main input:checked").each(function(i) {
            console.log(i);
            if ($(this).val() + "" !== "") {
                ids.push($(this).val());
            }
        });
        if (ids.length === 0) {
            layer.msg("至少选择一行进行操作!");
            return;
        }
        deletePlat(ids.join(","));
    }

    /**
     * 删除提交方法
     * @param ids 删除的ID列表字符串
     * */
    function deletePlat(ids) {
        console.log("delete_id:",ids);
        layer.confirm('你真的要删除勾选的行?', function(index) {
            layer.load();
            layer.close(index);
            $.ajax({
                url : deleteUrl,
                type : 'get',
                datatype : 'json',
                data : {
                    "ids" : ids
                },
                success : function(result) {
                    console.log(result);
                    if (parseInt(result.code) === 200) {
                        layer.msg(result.msg);
                        searchData();
                    } else {
                        layer.msg(result.msg);
                    }
                }
            });
        });
    }

    /**
     * 搜索方法
     * */
    function searchData() {
        dataTable.ajax.reload(null, false);
    }

    /**
     * 清空表单信息
     */
    function clearFrom() {
        $('#submitForm')[0].reset();
    }

    /**
     * 编辑用户
     * @param id
     */
    function edit(id) {
        let form = $("#submitForm");
        document.querySelector("#password").setAttribute("placeholder","未更改");
        document.querySelector("#password").dataset.tag = "0";
        clearFrom();
        $.ajax({
            url:getRoleUrl,
            data:{"id": loginUser.id},
            success:(resByLoginUser)=>{
                $.ajax({
                    url: getRoleUrl,
                    data:{"id": $("#id").val()},
                    success:(resByUpdateUser)=>{
                        let str = "";
                        console.log(resByLoginUser);
                        console.log(resByUpdateUser);
                        let checkedArray = [];
                        if(resByLoginUser.data !== null){
                            resByLoginUser.data.forEach((o,k)=>{
                                checkedArray[k] = false;
                                if(resByUpdateUser.data !== null){
                                    for (let i = 0; i < resByUpdateUser.data.length; i++) {
                                        if(o.id === resByUpdateUser.data[i].id){
                                            checkedArray[k] = true;
                                            break;
                                        }
                                    }
                                }
                                let s = checkedArray[k] ? " checked='checked' " : "";
                                str +=
                                    "<label style='cursor: pointer'>" +
                                    "<input " +
                                    " type='checkbox'" +
                                    s +
                                    " name = 'role' " +
                                    " value='"+ o.roleName +"'/>"+ o.roleName + "</label>&#12288;";
                            });
                        }
                        console.log(checkedArray);
                        $("#role p").html(str);
                    }
                });
            }
        });

        //设置表单提交 地址
        form.attr("action", updateUrl);
        $.ajax({
            url: editUrl,
            type: 'get',
            datatype: 'json',
            data: {
                "id": id,
                "updateBy": loginUser.name
            },
            success : function(result) {
                // 单击修改按钮时触发
                layer.closeAll();
                $("#formShow").show();
                layer.open({
                    title : '修改',
                    type : 1,
                    area : [ '80%', '60%' ], //宽高s
                    content : $('#formShow')
                });
                //填充表单信息
                for (let d in result) {
                    let $obj = $("#" + d);
                    if ($obj.length > 0) {
                        let tagName = $obj[0].tagName;
                        if (tagName == "IMG") {
                            $obj.attr("src", "" + result[d] + "");
                        } else {
                            $obj.val(result[d] + "");
                        }
                    }
                }
            }
        })
    }

    /**
     * 提交表单
     */
    function submitFrom() {
        // alert("101010");
        let form = $("#submitForm");
        layer.load();
        let options = {
            type : 'post',
            data:{"createBy": loginUser.name},
            success : function(data) {
                layer.closeAll();
                if (parseInt(data.code) === 200) {
                    searchData();
                } else {
                    layer.msg(data.msg);
                }
            }
        };
        form.ajaxSubmit(options);
    }

    /**
     * 添加用户
     */
    function add() {
        clearFrom();
        let form = $("#submitForm");
        document.querySelector("#password").setAttribute("placeholder","");
        form.attr("action", addUrl);
        $("#formShow").show();
        document.querySelector("#password").dataset.tag = "1";
        $.ajax({
            url:getRoleUrl,
            data:{"id": loginUser.id},
            success:(res)=>{
                console.log(res);
                let str = "";
                if(res.data !== null){
                    res.data.forEach((o, k) => {
                        str +=
    `<input type="checkbox" name="role" value="${o.roleName}"/> ${o.roleName}&#12288;`;
                    });
                }
                $("#role p").html(str);
            }
        });
        layer.open({
            title : '添加',
            type : 1,
            area : [ '80%', '60%' ], //宽高s
            content : $('#formShow')
        });
    }
</script>
</body>
</html>